#pragma once

#include <QVector>
#include "info.hpp"
#include <QJsonDocument>
#include <QJsonArray>
#include "conn.hpp"
#include "except.hpp"

namespace cloud
{

class Data
{
public:
    Data() : _infos(new QVector<Info>)
    {}

    void getData(QVector<Info>*& infos)
    {
        // Get and parser record data
        HttpConn conn;
        if (parserData(conn.request(QUrl(conn._svr_addr + "/record"))))
            infos = _infos;
        else
            infos = nullptr;
    }

private:
    bool parserData(const QByteArray& data)
    {
        QJsonParseError err;
        QJsonDocument doc = QJsonDocument::fromJson(data, &err);

        if (data.isEmpty() || data == _last_data) // If data before and after are equal, return false
            return false;

        _last_data = data; // update the last data

        if (doc.isNull()) ERROR("parser json error: " + err.errorString());
        if (!doc.isArray()) ERROR("json data error, is not a array");

        _infos->clear();
        for (const QJsonValue &val: doc.array())
            _infos->push_back(Info().deserialize(val));

        return true;
    }
private:
    QVector<Info>* _infos;
    QByteArray _last_data; // Save the last response data,
                           // update the data model when the data changes.
                           // Cause every time we refresh data , the program will freeze.
};

}
